package cn.schoolwow.workflow.module.task.query.kit;

import cn.schoolwow.quickdao.domain.database.dql.condition.Condition;
import cn.schoolwow.quickdao.domain.database.dql.response.PageVo;
import cn.schoolwow.quickflow.domain.FlowContext;
import cn.schoolwow.workflow.domain.task.WorkFlowTaskQuery;
import cn.schoolwow.workflow.domain.task.WorkFlowTaskResponse;
import cn.schoolwow.workflow.module.common.domain.QuickWorkFlowConfig;
import cn.schoolwow.workflow.module.task.query.flow.SetTaskQueryConditionFlow;
import cn.schoolwow.workflow.module.task.query.service.GetPagingTaskListServiceFlow;
import cn.schoolwow.workflow.module.task.query.service.GetTaskListServiceFlow;

import java.util.List;

public class WorkFlowTaskQueryServiceImpl implements WorkFlowTaskQueryService {
    private QuickWorkFlowConfig quickWorkFlowConfig;

    public WorkFlowTaskQueryServiceImpl(QuickWorkFlowConfig quickWorkFlowConfig) {
        this.quickWorkFlowConfig = quickWorkFlowConfig;
    }

    @Override
    public long getWorkFlowTaskCount(WorkFlowTaskQuery workFlowTaskQuery) {
        FlowContext flowContext = quickWorkFlowConfig.workflow.startFlow(new SetTaskQueryConditionFlow())
                .putCurrentCompositeFlowInstanceData(workFlowTaskQuery)
                .execute();
        Condition condition = flowContext.checkInstanceData(Condition.class);
        long count = condition.execute().count();
        return count;
    }

    @Override
    public WorkFlowTaskResponse getSingleWorkFlowTask(WorkFlowTaskQuery workFlowTaskQuery){
        PageVo<WorkFlowTaskResponse> pageVo = getWorkFlowTaskPagingList(workFlowTaskQuery,1,100);
        if(null==pageVo||null==pageVo.getList()||pageVo.getList().isEmpty()){
            return null;
        }
        if(pageVo.getTotalSize()>1){
            throw new IllegalArgumentException("期望获取单个分配任务，但是实际任务个数大于1!实际任务个数:"+pageVo.getTotalSize());
        }
        return pageVo.getList().get(0);
    }

    @Override
    public List<WorkFlowTaskResponse> getWorkFlowTaskList(WorkFlowTaskQuery workFlowTaskQuery) {
        FlowContext flowContext = quickWorkFlowConfig.workflow.startFlow(new GetTaskListServiceFlow())
                .putCurrentCompositeFlowInstanceData(workFlowTaskQuery)
                .execute();
        List<WorkFlowTaskResponse> list = flowContext.getData("list", List.class);
        return list;
    }

    @Override
    public PageVo<WorkFlowTaskResponse> getWorkFlowTaskPagingList(WorkFlowTaskQuery workFlowTaskQuery, int pageNumber, int pageSize){
        FlowContext flowContext = quickWorkFlowConfig.workflow.startFlow(new GetPagingTaskListServiceFlow())
                .putCurrentCompositeFlowInstanceData(workFlowTaskQuery)
                .putCurrentCompositeFlowData("pageNumber", pageNumber)
                .putCurrentCompositeFlowData("pageSize", pageSize)
                .execute();
        PageVo<WorkFlowTaskResponse> pageVo = flowContext.checkData("pageVo", PageVo.class);
        return pageVo;
    }

}
